/* ***************************************************
 * 
 * 编写人: 董书承等
 * 文件目的: 配置基本shell环境以及shell窗口, 已承接用户
 *          命令并执行.
 * 文件状态: 调整完毕
 * 
 * 
 * ***************************************************
*/
# include "shEnv.hh"
# include <string>
# include <cstdlib>
# include <vector>
# include <unistd.h>
# include "stdIn.hh"
# include "status.hh"
# include "demsStr.hh"
# include "dlCommd.hh"
# include <pwd.h>

int createEnv(std::string name)
{
    printf("环境已经成功创建!\n");
    return SUCCESS;
}

void commd(void)
{
    passwd* pwd;
    pwd = getpwuid(getuid());
    std::string userName = pwd->pw_name;

    std::string cmd;
    std::FILE * cmdfle;

//    std::string __BuildPlace;
//    char tmpbdpc[5012];
//    getcwd(tmpbdpc, sizeof(tmpbdpc));
//    __BuildPlace = tmpbdpc;

//    std::system(("mkdir -p " + __BuildPlace + "/temp/.data/dems/histCommand").c_str()); //build 文件夹下创建这个玩意
    std::system("mkdir -p ~/.data/dems/histCommand");
//    std::system(("cp ~/.data/dems/histCommand/hist.dms " + __BuildPlace + "/temp/.data/dems/histCommand/hist.dms -f\ "
//                                                                    "2> /dev/null").c_str());

    while(1)

    {
        cmdfle = std::fopen(("/home/" + userName + "/.data/dems/histCommand/hist.dms").c_str(), "a");
        // 获取当前路径
        char buf[1024];
        getcwd(buf, sizeof(buf));
        std::string bufStr(buf);
        //插入提示符
        std::cout << "[dems/KBL] " << bufStr << "$ ";
        // 等待输入
        cmd = getCommand();

        if (cmdfle == NULL)
        {
            std::printf("文件打开失败\n");
        }
        
        // std::cout << cmd << std::endl;
        if (cmd != "exit")
        {
            std::vector <std::string> cmdNparam;
            std::string spcmd;
            std::fputs((cmd+"\n").c_str(), cmdfle);
            std::fclose(cmdfle);
            std::putchar(10);
            // 分离参数
            cmdNparam = strSplit(cmd, " ");
            spcmd = cmdNparam[0];
            std::vector <std::string> paramVec(cmdNparam.begin()+1, cmdNparam.end());
            // 送命令处理处处理
            dShell::commd(spcmd, paramVec);
            
        }
        if(cmd == "exit")
        {
            std::fputs((cmd+"\n").c_str(), cmdfle);
            std::fclose(cmdfle);
//            std::system(("cp " + __BuildPlace + "/temp/.data/dems/histCommand/hist.dms ~/.data/dems/histCommand/hist.dms -f 2> /dev/null").c_str());
//            std::system(("rm -rf " + __BuildPlace + "/temp/ 2> /dev/null").c_str());
            return;
        }



    }
}